<template>
    <div class="exclude-page">
        <div class="content">
            <!-- <div class="pic">
                <van-image width="375px" fit="contain" :src="user" alt="" />
            </div> -->

            <main class="main">
                <p class="title" v-if="allData?.title">{{ allData?.title }}</p>
                <article class="article">
                    <!-- <p>尊敬的先生/女士:</p> -->
                    <div class="book" id="reDescription">
                        <!-- {{ allData?.description }} -->
                    </div>
                </article>
                <!-- <div class="obj" v-if="allData?.questions.length">
                <p class="answer_title">本次共 {{ allData?.questions.length }}题，请填写。</p>
            </div> -->

                <div class="test" v-for="v, k in allData?.questions" :key="v.id">
                    <div class="single" v-if="v.topic_type == 1 && v.display == '1'">
                        <div>
                            <div class="single_title"> <span class="require" v-if="v.is_required == 1">*</span>
                                {{ count(k) }}.{{ v.topic_name }}
                            </div>
                            <div class="secondTitle" v-if="v.tip">({{ v.tip }})</div>
                            <div style="padding-left: 30px;">
                                <van-radio-group v-model="v.checkOption" v-for="value, key in v.options" shape="dot"
                                    disabled>
                                    <van-radio :name="value.options_id" style="margin-bottom: 10px;">{{
                                        value.options_name
                                        }}</van-radio>
                                </van-radio-group>
                            </div>
                            <van-divider
                                :style="{ color: '#D8D8D8', borderColor: '#999', width: '90%', margin: '20px auto', }">
                            </van-divider>
                        </div>
                    </div>

                    <div class="mutl">
                        <div v-if="v.topic_type == 3 && v.display == '1'">
                            <div class="mutl_title"> <span class="require" v-if="v.is_required == 1">*</span>{{ count(k)
                                }}.
                                {{
                                    v.topic_name
                                }}
                            </div>
                            <div class="secondTitle" v-if="v.tip">({{ v.tip }})</div>
                            <div style="padding-left: 30px;">
                                <van-checkbox-group v-model="v.checkOption" v-for="value, key in v.options" disabled>
                                    <van-checkbox :name="value.options_id" shape="square"
                                        style="margin-bottom: 10px;">{{ value.options_name
                                        }}</van-checkbox>
                                </van-checkbox-group>
                            </div>
                            <van-divider
                                :style="{ color: '#D8D8D8', borderColor: '#999', width: '90%', margin: '20px auto', }">
                            </van-divider>
                        </div>
                    </div>

                    <div class="single_text">
                        <div v-if="v.topic_type == 2">
                            <div class="single_text_title"> <span class="require" v-if="v.is_required == 1">*</span> {{
                                count(k) }}.
                                {{
                                    v.topic_name }}</div>
                            <div class="secondTitle" v-if="v.tip">({{ v.tip }})</div>
                            <van-cell-group inset>
                                <van-field class="single_border" disabled v-model="v.answerText" placeholder="请输入内容" />
                            </van-cell-group>
                            <van-divider
                                :style="{ color: '#D8D8D8', borderColor: '#999', width: '90%', margin: '-2px auto', }">
                            </van-divider>
                        </div>
                    </div>

                    <div class="mutl_text">
                        <div v-if="v.topic_type == 4">
                            <div class="leave">
                                <div class="leave_title"> <span class="require" v-if="v.is_required == 1">*</span> {{
                                    count(k)
                                }}.
                                    {{
                                        v.topic_name }}
                                </div>
                                <div class="secondTitle" v-if="v.tip">({{ v.tip }})</div>
                                <div class="leave_message">
                                    <van-cell-group inset>
                                        <van-field class="mutl_border" disabled v-model="v.answerText" rows="6" clearable
                                            autosize type="textarea" maxlength="500" placeholder="请输入内容"
                                            show-word-limit />
                                    </van-cell-group>
                                </div>
                            </div>
                            <van-divider
                                :style="{ color: '#D8D8D8', borderColor: '#999', width: '90%', margin: '30px auto', }">
                            </van-divider>
                        </div>
                    </div>
                </div>
            </main>

            <!-- <div class="submit"><van-button type="primary" size="large" @click="throttle(submit)">提交</van-button></div> -->
        </div>
    </div>
</template>

<script setup lang="ts">
import { showToast } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { throttle } from '@/util/index'
import user from '@/assets/images/user.png'
import { useIndexStore } from '@/store/index'
import { POSTmyData, getData,getAnswer } from '@/api/index1'

import FingerprintJS from '@fingerprintjs/fingerprintjs';
// import mockJson from './mockJson'
const route = useRoute()
const router = useRouter()
const store = useIndexStore()


let allData = ref<Data>()
let t = ref()
var visitorId = '';

// let reDescription = ref(null)
async function mockData() {

    try {
        // 加载 FingerprintJS
        const fp = await FingerprintJS.load();
        // 获取 FingerprintJS 的结果
        const result = await fp.get();
        visitorId = result.visitorId;
        // console.log(visitorId, "数据");

        // 处理本地存储中的数据
        let overlist = localStorage.getItem("overlist");
        if (overlist) {
            let odd = JSON.parse(overlist);
            let temid = route.query.template_id;
            let hosid = route.query.hosp_id;
            let zuhe = hosid + "/" + temid;
            odd.forEach((el) => {
                if (el == zuhe) {
                    router.push({ name: 'notice_successover' });
                }
            });
        }

        // 获取问卷数据
        const temp_id = route.query.template_id;

        if (temp_id) {
            let objsub = {
                id: route.query.template_id,
                source: route.query.source,
                hospitalId: route.query.hosp_id,
                visitorId: visitorId
            };

            let res = await getData(objsub);
            allData.value = res.data;
            window.document.title = allData.value.title
            localStorage.setItem('title',allData.value.title );
            // console.log(res, "1111")
            if (res.code == 209) {
                router.push({ name: 'notice_successover' });
            }
            t.value = allData.value.description.replace(/\n/g, '<br><div style="text-indent: 2em;">')
            //console.log();
            document.getElementById('reDescription').innerHTML = t.value
            allData.value?.questions.forEach(v => {
                if (v.topic_type == 1) {
                    v['checkOption'] = ref();
                }
                if (v.topic_type == 3) {
                    v['checkOption'] = ref([]);
                }
                if ([2, 4].includes(v.topic_type)) v['answerText'] = '';
            });
        } else {
            showToast('问卷ID不存在，请刷新后重试');
        }
    } catch (error) {
        console.error('加载 FingerprintJS 或获取数据时发生错误:', error);
        // showToast('发生错误，请重试');
    }
}
const init = async () => {
    await mockData()
    getQiwei()
}

async function getQiwei() {
    let id = route.query.quesResultId || ''
    let res = await getAnswer(id)
    //console.log(111);
    
    if (res.code == 200) {
        let answer_ids = res.data.questions.map(val => {
            if (val.topicType == 1) {  //单选的答案
                return val.options[0].optionsId
            }
            if (val.topicType == 3) { //多选的答案
                if (val.options && val.options.length > 0) {
                    return val.options.map(item => item.optionsId)
                }
            }
            if (val.topicType == 2 || val.topicType == 4) {   //单独处理 2，4类型
                return {
                    answerText: val.answerText,
                    id: val.id
                }
            }

        })

        // console.log(answer_ids);
        allData.value?.questions.forEach(v => {  //答案和题目对应
            res.data.questions.map(val => {  //展开收起处理
                if (v.topic_name == val.topicName) {
                    v.display = val.display
                }
               // console.log(v);
            })

            if ([2, 4].includes(v.topic_type)) {  //单行，多行文本答案赋值
                //console.log(val.id);
                answer_ids.map(items => {  //单选多选回显处理
                    // console.log(items.id == val.id,val.answerText);
                    if (items.id == v.id) {
                        //console.log(val);
                        v.answerText = items?.answerText
                      //  console.log(val.answerText.toString());

                    }
                })
            }

            // console.log(v);
            v.options.forEach(vals => {
                answer_ids.map(id => {  //单选多选回显处理
                    //  console.log(v.topic_type);

                    if (vals.options_id == id || Array.isArray(id) && id.includes(vals.options_id)) {
                        v.checkOption = id
                    }
                    // if(val.options_id == id && val.)
                })
            })

        })

    } else {
        showToast('获取数据失败，请重试')
    }

}

let count = computed((key) => {
    return (key) => {
        if (key > 0) {
            let arr = allData.value?.questions.slice(0, key)
            let num = arr.reduce((pre, cur) => {
                if (cur.display == '0') pre++
                return pre
            }, 0)
            //  console.log(num);
            return allData.value?.questions[key].sort - num
            //return num + 1
        }
        return key + 1
    }
})


//单选结果赋值
const singleSelect = (question, id: string | number, next: { id: string | number, type: number }) => {
    // console.log(question,id, next);
    allData.value?.questions.forEach(v => {
        // console.log(v.id, next?.id);
        if (next?.id && next.id == v.id) {  //有next值，直接显示
            let findId = allData.value?.questions.find(val => (val.id == next.id))
            // console.log(findId);
            v.display = "1"
        }
        if (next == null && id == question.id) {   //没有next值，选择当前题目后，找到有next值的题目，隐藏
            let hiddenId = question.options.find(opt => (opt.next !== null))
            //   console.log(hiddenId);
            hiddenId && Object.values(allData.value.questions).forEach((question, key) => {
                if (question.id == hiddenId.next.id) {
                    question.display = '0'
                }
            })
        }
    })
}

//多选结果赋值
const mutleSelect = (id: string | number, next: { id: string | number, type: number }) => {
    //console.log(id, next);
    allData.value?.questions.forEach(v => {
        // console.log(v.id, next.id);
        if (next?.id && next.id == v.id) {
            v.display == "1" ? v.display = "0" : v.display = "1"  //多选可以用三元，但是多选不能用
        }
    })
}


let startTime: number = Date.now();
const formateSeconds = (endTime: number): string => {  //秒转分钟和小时
    let secondTime: number = parseInt(endTime)//将传入的秒的值转化为Number
    let min = 0// 初始化分
    let h = 0// 初始化小时
    let result = ''
    if (secondTime >= 60) {//如果秒数大于等于60，将秒数转换成整数
        min = parseInt(secondTime / 60)//获取分钟，除以60取整数，得到整数分钟
        secondTime = parseInt(secondTime % 60)//获取秒数，秒数取佘，得到整数秒数
        if (min >= 60) {//如果分钟大于等于60，将分钟转换成小时
            h = parseInt(min / 60)//获取小时，获取分钟除以60，得到整数小时
            min = parseInt(min % 60) //获取小时后取佘的分，获取分钟除以60取佘的分
        }
    }
    if (h) {
        result = `${h.toString().padStart(2, '0')}时:${min.toString().padStart(2, '0')}分:${secondTime.toString().padStart(2, '0')}秒`
    } else if (min) {
        result = `${min.toString().padStart(2, '0')}分:${secondTime.toString().padStart(2, '0')}秒`
    } else {
        result = `${secondTime.toString().padStart(2, '0')}秒`
    }
    return result
}

function showCount(key) {
    if (key > 0) {
        let arr = allData.value?.questions.slice(0, key)
        let num = arr.reduce((pre, cur) => {
            if (cur.display == '0') pre++
            return pre
        }, 0)
        //  console.log(num);
        return allData.value?.questions[key].sort - num
        //return num + 1
    }
    return key + 1
}

const userOptionList = ref<questionPost[]>([])
const submit = async () => {
    showToast('预览页面无法提交答卷')
    return
    userOptionList.value = []
    const questions = Object.values(allData.value!.questions)
    let pass = questions && questions.map((v, k) => {
        // console.log(v.is_required,v.topic_type);
        if (v.is_required == 1 && v.display == '1' && [1, 3].includes(v.topic_type)) {  //校验单选和多选
            if (v.checkOption.length == 0) {
                showToast({ message: `${showCount(k)}.${v.topic_name}请选择一个选项`, duration: 3000 })
                return false
            }
        }
        if (v.is_required == 1 && v.display == '1' && [2, 4].includes(v.topic_type)) {  //校验多行和单行文本
            if (v?.answerText?.length == 0) {
                showToast({ message: `${showCount(k)}.${v.topic_name}请选择填写题目`, duration: 3000 })
                return false
            }
        }

        if (v.topic_type == 1) {  //单选
            userOptionList.value.push({ "questionid": v.id.toString(), "answerText": '', "question_type": v.topic_type.toString(), "option_id": v.checkOption.toString() })
        }
        if (v.topic_type == 3) {  //多选
            userOptionList.value.push({ "questionid": v.id.toString(), "answerText": '', "question_type": v.topic_type.toString(), "option_id": v.checkOption.join() })
        }
        if ([2, 4].includes(v.topic_type)) {  //单行文本和多行文本
            userOptionList.value.push({ "questionid": v.id.toString(), "answerText": v.answerText!, "question_type": v.topic_type.toString(), "option_id": '' })
        }

    })
    if (!pass.includes(false)) {  //如果校验通过，则提交数据
        postData(userOptionList.value)
        // console.log(555,pass);
    }
}
async function postData(params: questionPost[]) {  //正常提交数据
    const temp_id = route.query.template_id
    // router.push({ name: 'notice_success', params: { template_id: temp_id } })
    let source = { "source": allData.value?.source }
    let hosp_id = { "hospitalId": allData.value?.hospitalId }
    let template_id = { "template_id": allData.value?.template_id }
    let visitorIda = { "visitorId": visitorId }

    let data = { questions: params, ...source, ...hosp_id, ...template_id, ...visitorIda }
    let res = await POSTmyData(data)
    if (res.code == 209) {
        showToast(res.msg)
    }
    if (res.code == 200) {
        //清空本地数据
        localStorage.setItem('hosid', allData.value.hospitalId);

        userOptionList.value = []
        let overid = []
        store.testData = []
        let oootian = localStorage.getItem("overlist")
        if (oootian) {
            overid = JSON.parse(oootian)
            let item = ""
            item = allData.value.hospitalId + "/" + allData.value.template_id
            overid.push(item)

            localStorage.setItem('overlist', JSON.stringify(overid));
        } else {
            overid = []
            let item = ""
            item = allData.value.hospitalId + "/" + allData.value.template_id
            overid.push(item)

            localStorage.setItem('overlist', JSON.stringify(overid));
        }

        allData.value = []
        localStorage.setItem('submit', "1");


        router.push({ name: 'notice_success', query: { num: res.data } })
    }
}


function checkPoint() {  //用户填表后，拼接数据并且实时保存数据
    userOptionList.value = []
    const questions = Object.values(allData.value!.questions)
    let pass = questions && questions.map((v, k) => {
        if (v.topic_type == 1 && v.checkOption) {  //单选,有值才入栈
            userOptionList.value.push({ "questionid": v.id.toString(), "answerText": '', "question_type": v.topic_type.toString(), "option_id": v.checkOption.toString() })
        }
        if (v.topic_type == 3 && v.checkOption) {  //多选,有值才入栈
            userOptionList.value.push({ "questionid": v.id.toString(), "answerText": '', "question_type": v.topic_type.toString(), "option_id": v.checkOption.join() })
        }
        if ([2, 4].includes(v.topic_type && v.answerText)) {  //单行文本和多行文本,有值才入栈
            userOptionList.value.push({ "questionid": v.id.toString(), "answerText": v.answerText!, "question_type": v.topic_type.toString(), "option_id": '' })
        }
    })
    if (userOptionList.value.length > 0) {
        store.testData = allData.value
    }
}

//定时存储到localstorge
let interval
onMounted(() => {
    init() //初始化数据
    interval = setInterval(() => {
        checkPoint()  //用户填表后，拼接数据并且实时保存数据
        if (store.testData?.questions?.length > 0) {//如果本地存数据了，就回显
            allData.value = store.testData
        }
    }, 500)
})
onUnmounted(() => clearInterval(interval)) //销毁时清除定时器


</script>
<style>
.van-radio {
    margin-bottom: 18px !important;
}
</style>
<style scoped lang="scss">
.exclude-page {
    background-color: #f2f2f2;
    min-height: 100vh;

    .content {
        width: 375px;
        margin: 0 auto;
        // padding-top: 48px;
        background-color: white;

        .pic {
            position: relative;
            z-index: 1;
        }

        .main {
            position: relative;
            z-index: 2;
           // margin-top: 10px;
            background-color: #fff;
            // height: 100vh;
            border-radius: 30px;

            .title {
                padding: 18px 44px 15px 44px;
                margin: 0 auto;
                text-align: center;
                width: 287px;
                font-size: 22px;
                font-weight: 500;
                color: #3D3D3D;
                line-height: 50px;
            }

            .article {
                margin: 0 auto;
                width: 337px;
                // height: 102px;
                font-size: 16px;
                font-family: Source Han Sans CN-Regular, Source Han Sans CN;
                font-weight: 400;
                color: #999999;
                line-height: 1.5;

                .book {
                    //  margin-top: 20px;
                    margin-bottom: 20px;
                }
            }

            .obj {

                .answer_title {
                    margin: 30px 0 28px 20px;
                    font-size: 16px;
                    font-weight: 400;
                    color: #999999;
                    line-height: 20px;
                }
            }

            .require {
                color: red;
                padding-right: 5px;
                line-height: 15px;
            }

            .test {
                // margin-left: 10px;

                .secondTitle {
                    padding-left: 20px;
                    padding-bottom: 10px;
                    color: #999999;
                    font-size: 14px;
                }

                .single {
                    font-size: 18px;
                    font-weight: 400;
                    color: black;
                    line-height: 1.6;
                    padding-top: 15px;

                    .single_title {
                        padding-left: 20px;
                        padding-right: 20px;
                        padding-bottom: 15px;
                    }
                }

                .mutl {
                    font-size: 16px;
                    font-weight: 400;
                    color: black;
                    line-height: 1.5;

                    .mutl_title {
                        padding-left: 20px;
                        padding-right: 20px;
                        padding-bottom: 15px;
                    }
                }

                .single_text {
                    font-size: 16px;
                    font-weight: 400;
                    color: black;
                    line-height: 1.5;

                    .single_text_title {
                        padding-left: 20px;
                        padding-right: 20px;
                        padding-bottom: 15px;
                        // :deep .van-cell {
                        //     border: 1px solid #ccc !important;
                        // }
                    }

                    .single_border {
                        :deep .van-cell {
                            border: none;
                        }
                    }


                }

                .mutl_text {
                    .leave {

                        .leave_title {
                            font-size: 18px;
                            font-weight: 400;
                            color: black;
                            line-height: 1.6;
                            padding-left: 20px;
                            padding-right: 20px;
                            padding-bottom: 20px;
                        }

                        .leave_message {
                            // margin-right: 25px;
                            //  padding-bottom: 5px;

                            .mutl_border {
                                border: 1px solid #ccc !important;
                                border-radius: 10px;
                            }
                        }
                    }
                }
            }
        }



        .submit {
            margin: 0 auto;
            width: 85%;
            padding: 20px 0;
        }
    }
}

:v-deep(.van-cell-group--inset) {
    border-radius: 2px !important;
}

:v-deep(.van-radio__icon--dot__icon) {
    transform: translate(-53%, -54%) !important;
    // width: 15px !important;
    // height: 15px !important;
}

// ::v-deep(.van-radio__icon--dot){
//     width: 14px !important;
//     height: 14px !important;
// }</style>
